<?php
/**
 * author:zhihong.yin
 * 注意：必须先将存量媒资注入到cms
 * 1.创建cms媒资包栏目
 * 2.主媒资上下线
 */
error_reporting(E_ALL);
set_time_limit(0);
include_once dirname(dirname(dirname(dirname(dirname(__FILE__)))))."/common.php";
define('CP_ID','jycm');
define('SP_ID','jscn_bkzx');
//cms创建媒资包栏目的接口
define('IMPORT_CMS_CATEGORY_URL','http://118.25.209.242:93/starcor/cms/nn_cms/api/k/index.php?m=sync_asset_category/k380_b_1&a=add');
//上下线接口
define('IMPORT_CMS_ONLINE_URL','http://118.25.209.242:93/starcor/cms/nn_cms/nn_cms_manager/service/asset_import/k23/asset_api.php');
class import_cms
{
    //db实例
    private $db;
    //curl句柄
    private $res_curl;
    private $cp_id;
    private $sp_id;
    
    //媒资包栏目名称
    private $asset_packet_name = '融合AAA专用测试';

    //媒资包id
    private $asset_packet_id;

    public function  __construct($api_url)
    {
        $this->db = m_config::get_dc()->db();
        $this->cp_id = CP_ID;
        $this->sp_id = SP_ID;

        $this->res_curl = curl_init();
        curl_setopt($this->res_curl, CURLOPT_URL,$api_url);
        curl_setopt($this->res_curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($this->res_curl, CURLOPT_CONNECTTIMEOUT, 5);
        curl_setopt($this->res_curl, CURLOPT_TIMEOUT, 5);
    }

    /**
     * [import_cms_category description]  栏目注入媒资包栏目
     * @return [type] [description]
     */
    public  function import_cms_category()
    {
        for( $circle_num = 0;true;$circle_num += 10 )
        {
            $arr_category = $this->get_categorys($circle_num);
            if( empty($arr_category) || !is_array($arr_category) )
            {
                break;
            }
            
            foreach( $arr_category as $category )
            {
                $arr_data  = [
                    'category_id'=>$category['nns_id'],
                    'parent_category'=>$category['nns_parent_id'],
                    'name'=>$category['nns_name'],
                    'sort'=>'',
                    'display'=>1
                ];

                if( empty($category['nns_parent_id']))
                {
                    //首个执行的，且父级在cms中没有关联数据，这里设为xxx，不可设为空，媒资包id就是这里的栏目id
                    $this->asset_packet_id = $category['nns_id'];
                    $arr_data  = [
                        'category_id'=> $category['nns_id'],

                        'parent_category'=>'xxx',
                        'name'=>$this->asset_packet_name,
                        'sort'=>'',
                        'display'=>1
                    ];
                }

                $post_data['data'] = json_encode([$arr_data]);
                curl_setopt($this->res_curl, CURLOPT_POSTFIELDS, $post_data);
                $data = curl_exec($this->res_curl);
                echo $arr_data['name'];
                var_dump($data);
                $curl_info = curl_getinfo($this->res_curl);

                //组装信息，记录日志
                $curl_info['nns_category_id'] = $category['nns_id'];
                $curl_info['nns_category_name'] = $category['nns_name'];
                $curl_info['nns_parent_id'] = $category['nns_parent_id'];

                if( !isset($curl_info['http_code']) || $curl_info['http_code'] != 200 )
                {
                    $this->returnMsg("栏目注入失败，栏目id为{$category['nns_id']},栏目名称为{$category['nns_name']}");
                }
            }
        }
    }

    
    /**
     * [asset_on_off_line description]  媒资包主媒资上下线
     * @return [type] [description]
     */
    public function asset_on_off_line()
    {
        while(true)
        {
            $sql = "select nns_category_id,nns_series_id from nns_asset_source_incre
                                        where nns_state !=3
                                         order by nns_id
                                         limit 0,1000";

            $res = nl_query_by_db($sql,$this->db);
            if( empty($re) || !is_array($re) )
            {
                break;
            }

            foreach( $res as $re )
            {
                $post_data=[
                    'func'=>'unline_assets',
                    'id'=>$re['nns_series_id'],
                    'cp_id'=>CP_ID,
                    'assets_unline'=>0,
                    'assets_id_type'=>0,
                    'assets_category'=>"{$this->asset_packet_id}|{$re['nns_category_id']}"
                ];
                curl_setopt($this->res_curl, CURLOPT_POSTFIELDS, $post_data);

                $curl_res = curl_exec($this->res_curl);
                var_dump($curl_res);
                $curl_info = curl_getinfo($this->res_curl);

                if( isset($curl_info['http_code']) && $curl_info['http_code'] == 200 )
                {
                    //上下线成功
                    $unline_status = 3;
                }
                else
                {
                    $unline_status = 0;
                    //失败写入日志
                    $path_log = dirname(dirname(dirname(dirname(dirname(dirname(__FILE__))))))."/data/script/cp_{$this->cp_id}/sp_{$this->sp_id}";
                    if( !is_dir($path_log) )
                    {
                        mkdir($path_log,0777,true);
                    }
                    $re=file_put_contents($path_log.'/unline_fail.txt',var_export($curl_info,true).PHP_EOL,FILE_APPEND);
                }

                $sql = "update nns_asset_source_incre set nns_state = {$unline_status}  where nns_id = {$re['nns_id']}";
                nl_execute_by_db($sql,$this->db);

            }
        }
    }

    /**
     * @param $limit_start
     * @return bool
     * 获取栏目信息 
     */
    public function get_categorys($limit_start)
    {
        $sql = "select * from nns_asset_category_incre 
                          order by nns_deep asc
                          limit {$limit_start},10";

        return nl_query_by_db($sql,$this->db);
    }

    /**
     * @param $status
     * @param $category_info
     * curl请求后改变栏目的状态
     */
    private function change_category_status($status,$category_info)
    {
        $sql = "update nns_asset_category_incre
                    set nns_status = {$status}
                    where nns_id = '{$category_info["nns_id"]}'
                    and nns_parent_id = '{$category_info["nns_parent_id"]}'";
        nl_execute_by_db($sql,$this->db);
    }
    
    /**
     * 关闭资源
     * @return [type] [description]
     */
    public function __destrunct()
    {
        curl_close($this->res_curl);
    }

    /**
     * @param $msg     脚本信息
     * @param null $type    信息类型   die 终止信息  |  其他  一般提示信息
     * 脚本执行信息
     */
    public function returnMsg($msg,$type = null)
    {
        if( is_string($msg) && !empty($msg))
        {
            echo str_pad($msg,50,'-',STR_PAD_BOTH).PHP_EOL;
            if($type == 'die')
            {
                echo str_pad('进程结束',50,'-',STR_PAD_BOTH).PHP_EOL;
                exit;
            }
        }
    }
}
//栏目注入
$obj = new import_cms(IMPORT_CMS_CATEGORY_URL);
$obj->returnMsg('开始栏目注入');
$obj->import_cms_category();
$obj->returnMsg('栏目注入结束');
unset($obj);

//主媒资上下线
$obj = new import_cms(IMPORT_CMS_ONLINE_URL);
$obj->returnMsg('开始媒资上下线');
$obj->asset_on_off_line();
$obj->returnMsg('媒资上下线结束');

